package com.macro.mall.portal.controller;

import com.alibaba.fastjson.JSONObject;
import com.macro.mall.common.api.CommonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.Random;

/**
 * 微信相关Controller
 * Created by macro on 2018/8/3.
 */
@Slf4j
@RestController
@Api(tags = "WeChatController", description = "微信相关Controller")
@RequestMapping("/wechat")
public class WeChatController {

    @Autowired
    private RestTemplate restTemplate;


    @Value("${wechat.AppID}")
    private String appId;
    @Value("${wechat.AppSecret}")
    private String appSecret;
    @Value("${wechat.getTicketUrl}")
    private String ticketUrl;
    @Value("${wechat.getAccessTokenUrl}")
    private String accessTokenUrl;

    @ApiOperation("获取微信相关信息")
    @RequestMapping(value = "/getWchatSignature", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult getWchatSignature(@ApiParam(value = "请求报文") @RequestBody String url) {

        /**1.获取 access_token*****************************************************************/
        String accessToken=getWXaccessToken();
        /**2.获取 jsapi_ticket*****************************************************************/
        String jsapiTicket=getWXJsapiTicket(accessToken);


        long timeStampSec = System.currentTimeMillis() / 1000;
        String timestamp = String.format("%010d", timeStampSec);
        String nonceStr = getRandomStr(16);

        String callUrl="";
        if(!StringUtils.isBlank(url)){
            JSONObject Body = JSONObject.parseObject(url);
            callUrl=Body.getString("url");
        }

        String[] urls = callUrl.split("#");
        String newUrl = urls[0];
        log.info("★★★★★★★★★★★★★★★  随机串 nonceStr= ："+nonceStr+"  获取签名URL  newUrl=" + newUrl+"  jsapi_ticket="+jsapiTicket+" timestamp="+timestamp);
        JSONObject respJson = new JSONObject();
        String[] signArr = new String[]{"url=" + newUrl, "jsapi_ticket=" + jsapiTicket, "noncestr=" + nonceStr, "timestamp=" + timestamp};
        Arrays.sort(signArr);
        String signStr = StringUtils.join(signArr, "&");
        String resSign = DigestUtils.sha1Hex(signStr);

        respJson.put("appId", appId);
        respJson.put("timestamp", timestamp);
        respJson.put("nonceStr", nonceStr);
        respJson.put("signature", resSign);

        return CommonResult.success(respJson);
    }
    private String getWXJsapiTicket(String accessToken) {
//        String ticket = redisClient.getStr(appId);
//        if (StringUtils.isBlank(ticket)) {
            String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + getWXaccessToken() + "&type=jsapi";
           String jsapiTicketUrl = ticketUrl+ "&access_token="+accessToken;
            String resp = restTemplate.getForObject(jsapiTicketUrl, String.class);
            JSONObject resJson = JSONObject.parseObject(resp);
            log.info("★★★★★★★★★★★★★★★获取到ticket：" + resJson.toJSONString());
            log.info("获取到ticket：" + resJson.getString("ticket"));
//            redisClient.setStr(appId, resJson.getString("ticket"), SystemConstants.ONE_HOURS * 2);
            return resJson.getString("ticket");
//        }
//        return ticket;
    }

    private String getWXaccessToken() {
        String url =  accessTokenUrl+ "&appid="+appId+"&secret="+appSecret;
        String resp = restTemplate.getForObject(url, String.class);
        JSONObject resJson = JSONObject.parseObject(resp);
        log.info("★★★★★★★★★★★★★★★获取到access_token：" + resJson.toJSONString());
        log.info("获取到access_token：" + resJson.getString("access_token"));
        return resJson.getString("access_token");
    }

    public static String getRandomStr(int length) {
        String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        int randomNum;
        char randomChar;
        Random random = new Random();
        // StringBuffer类型的可以append增加字符
        StringBuffer str = new StringBuffer();

        for (int i = 0; i < length; i++) {
            // 可生成[0,n)之间的整数，获得随机位置
            randomNum = random.nextInt(base.length());
            // 获得随机位置对应的字符
            randomChar = base.charAt(randomNum);
            // 组成一个随机字符串
            str.append(randomChar);
        }
        return str.toString();
    }
}
